package com.ruoyi.consumer.utils.pay;

import org.apache.http.Consts;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.SocketTimeoutException;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;


public class HttpClient {
    /**
     * 向指定 URL 发送json格式参数的POST方法的请求
     *
     * @param url  发送请求的 URL
     * @param json json格式请求参数
     * @return 所代表远程资源的响应结果
     */
    public static String postJson(String url, String json, Map<String, String> headMap) {
        String returnStr;
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse httpResponse = null;
        try {
            HttpPost post = new HttpPost(url);
            post.setConfig(RequestConfig.custom().setSocketTimeout(10000).setConnectTimeout(10000).build());
            httpClient = HttpClientBuilder.create().build();
            StringEntity s = new StringEntity(json, Consts.UTF_8);
            s.setContentType("application/json");
            if (headMap != null && headMap.size() > 0) {
                Set<String> keySet = headMap.keySet();
                for (String key : keySet) {
                    post.addHeader(key, headMap.get(key));
                }
            }
            post.setEntity(s);
            httpResponse = httpClient.execute(post);
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(),
                    StandardCharsets.UTF_8.name()));
            StringBuilder stringBuffer = new StringBuilder(100);
            String str;
            while ((str = reader.readLine()) != null) {
                stringBuffer.append(str);
            }
            returnStr = stringBuffer.toString();
            reader.close();
            return returnStr;
        } catch (SocketTimeoutException e) {

            System.out.println("地址: [{}]|参数: [{}] 读取超时"+ url+"::"+ json);
            return "";
        } catch (ConnectTimeoutException e) {
            System.out.println("地址: [{}]|参数: [{}] 连接超时"+ url+"::"+ json);
            return "";
        } catch (Exception e) {
            System.out.println("地址: [{}]|参数: [{}] 请求异常: [{}]"+ url+"::"+ json+"::"+ e);
            return "";
        } finally {
            HttpClientUtils.closeQuietly(httpResponse);
            HttpClientUtils.closeQuietly(httpClient);
        }
    }



}
